//
//  KZMakeExamVC.m
//  lg_zhinengbeikao_english
//
//  Created by 朱凯 on 2018/12/26.
//  Copyright © 2018 zhukai. All rights reserved.
//

#import "KZMakeExamVC_v2.h"


// view
#import "KZExamProgressView.h"  // 进度条
#import "KZExamItemView_v2.h"   // 试卷
#import "KZTimerView.h"         // 计时器



@interface KZMakeExamVC_v2 () <UIScrollViewDelegate>

@property (nonatomic, strong) NSMutableDictionary<NSString *, KZExamItemView_v2 *> *itemViews;

@property (nonatomic, strong) KZExamProgressView *progressView;
@property (nonatomic, strong) KZTimerView *timerView;
@property (nonatomic, strong) UIScrollView *scroll;

@end

@implementation KZMakeExamVC_v2
{
    NSInteger _maxCount;        // 最大题数
    NSMutableArray *_items;
    NSInteger _currentIndex;    // 当前显示的题目索引
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNaviUI];
    [self setupUI];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

#pragma mark - 创建视图
- (void)setupNaviUI {
    
    [self addLeftBackBarButtonItem];
    
    _timerView = [[KZTimerView alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    [_timerView setOnTimerStatusChanged:^(BOOL pausing) {
        NSLog(@"%@", pausing?@"暂停":@"恢复");
    }];
    [_timerView start:100 * 60 - 5];
    
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(0, 0, 24, 24);
    button1.tag = 1;
    [button1 setImage:[UIImage imageNamed:@"center"] forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(onSelectNaviItem:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.frame = CGRectMake(0, 0, 24, 24);
    button1.tag = 2;
    [button2 setImage:[UIImage imageNamed:@"center"] forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(onSelectNaviItem:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
    button3.frame = CGRectMake(0, 0, 24, 24);
    button1.tag = 3;
    [button3 setImage:[UIImage imageNamed:@"center"] forState:UIControlStateNormal];
    [button3 addTarget:self action:@selector(onSelectNaviItem:) forControlEvents:UIControlEventTouchUpInside];
    
    [self addNaviItemWithCustomViews:@[_timerView, button1, button2, button3] position:KZNavigationItemPositionModeRight];
}

- (void)setupUI {
    
    _progressView = [KZExamProgressView new];
    _progressView.totalIndex = 20;
    _progressView.index = 10;
    [self.view addSubview:_progressView];
    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.width.equalTo(self.view);
        make.height.mas_equalTo(35);
    }];
    
    _scroll = [UIScrollView new];
    _scroll.delegate = self;
    _scroll.pagingEnabled = true;
    [self.view addSubview:_scroll];
    [_scroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.equalTo(self.view);
        make.top.equalTo(self.progressView.mas_bottom);
        make.bottom.equalTo(self.view);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(0);
        }
    }];
    
    
    // 模拟数据
    _items = [NSMutableArray new];
    for (int i = 0; i < 10; i ++) {
        if (i % 4 == 0) {
            KZExamItemModel *model = [KZExamItemModel new];
            model.subject = @"你受学生会委托为校宣传栏“英语天地”写一则通知，请大家观看一部英文短片GrowingTogether，内容包括：\n1、短片内容：学校的发展；\n2、放映时间、地点；\n3、欢迎对短片提出意见。\n注意：\n1、词数100词左右；\n2、可以适当增加细节，以使行文连贯。";
            model.type = KZExamItemWritting;
            [_items addObject:model];
        } else if (i % 4 == 1) {
            KZExamItemModel *model = [KZExamItemModel new];
            model.subject = @"1. Can you help my sister with _ (dance)?\n2. Hellen wants _ (join) the basketball club.\n3. Can you _ (tell) _ (story)?\n4. My brother _ (go) to school at seven every day.\n5. What time does your father get _ (dress)?\n6. What time do you _ (usual) get up?\n7. Eating _ (quick) is not very good for us.\n8. What time _ your aunt usually go to _ (work)?";
            model.type = KZExamItemFilling;
            model.answerCount = 8;
            [_items addObject:model];
        } else if (i % 4 == 2) {
            KZExamItemModel *model = [KZExamItemModel new];
            model.subject = @"There is no surgical patient I cannot treat competently，_________ just as well as or better than any surgeon.";
            model.type = KZExamItemSelecting;
            model.optionsList = @[@{@"A": @"Hello",
                                    @"B": @"I like fishing.",
                                    @"C": @"Are you 18 years old?",
                                    @"D": @"How are you?",
                                    }];
            [_items addObject:model];
        } else if (i % 4 == 3) {
            KZExamItemModel *model = [KZExamItemModel new];
            model.subject = @"    These days it is found that school students hardly have any sports. Is it because they have no   1   in sports? It may not be true. They often say they have   2   more important things to do.\n    What are these important things? Exams! They have to   3__   themselves ready for all kinds of exams and tests in school. So many of them almost   4   bookworms(书呆子). In the past in the summer holidays, they could do   5   they liked, but now they have to   6__   all their time preparing. So   7   have kept them away from going in for sports.\n    Because of the pressure(压力) from   8   parents and teachers, they    9    to work harder and spend most of their time   10__   books. As for the students themselves, they don’t want to   11   the lessons because they want to further their studies. So it is necessary to give   __12   of their spare time to their studies and   13   up their school sports.\n    It’s true a good education cannot go without physical training, the  __14 _ is true, a quick mind hardly goes along with a   15   body. Without a strong body, you can never do anything well, how can you make great success in life?";
            model.type = KZExamItemSelecting;
            model.optionsList = @[@{@"A": @"Hello",
                                    @"B": @"I like fishing.",
                                    @"C": @"Are you 18 years old?",
                                    @"D": @"How are you?",
                                    },
                                  @{@"A": @"Hello",
                                    @"B": @"I like fishing.",
                                    @"C": @"Are you 18 years old?",
                                    @"D": @"How are you?",
                                    },
                                  @{@"A": @"Hello",
                                    @"B": @"I like fishing.",
                                    @"C": @"Are you 18 years old?",
                                    @"D": @"How are you?",
                                    }];
            [_items addObject:model];
        }
    }
    _maxCount = _items.count;
    _currentIndex = 0;
    _itemViews = [[NSMutableDictionary alloc] init];
    UIView *last = nil;
    for (int i = 0; i < 2; i ++) {
        KZExamItemView_v2 *view = [KZExamItemView_v2 new];
        view.model = _items[i];
        view.frame = CGRectMake(i * SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 35 - NAVIGATION_HEIGHT);
        [_scroll addSubview:view];
        last = view;
        _itemViews[[NSString stringWithFormat:@"%i", i]] = view;
    }
    
    _scroll.contentSize = CGSizeMake(self.view.width * _maxCount, SCREEN_HEIGHT - 35 - NAVIGATION_HEIGHT);
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    scrollView.scrollEnabled = false;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSInteger index = (NSInteger)(scrollView.contentOffset.x / scrollView.width);
    if (index == _currentIndex) {
        scrollView.scrollEnabled = true;
        return;
    } else {
        NSInteger number = index > _currentIndex ? NSIntegerMax : -NSIntegerMax;
        _currentIndex = index;
        
        [self pushToExamItemAtIndex:_currentIndex seekTo:number];
    }
}




- (void)pushToExamItemAtIndex:(NSInteger)index seekTo:(NSInteger)number {
    
    // 快捷取值
    CGFloat w = _scroll.width;
    CGFloat h = _scroll.height;
    
    // 选择快进到某题前的可视视图，可视视图会在创建完
    UIView *currentVisableView = _itemViews[[NSString stringWithFormat:@"%li", _currentIndex]];
    
    // 先把两侧的视图移除掉，仅保留现在可视的视图，用于滚动
    for (KZExamItemView_v2 *view in self.itemViews.allValues) {
        if (view != currentVisableView) {
            [view removeFromSuperview];
        }
    }
    
    // 记录当前要滑动到的位置的视图的引用
    KZExamItemView_v2 *indexView = nil;
    // 如果还未创建过，则创建
    if (_itemViews[[NSString stringWithFormat:@"%li", index]] == nil) {
        
        indexView = [KZExamItemView_v2 new];
        indexView.model = _items[index];
        [_scroll addSubview:indexView];
        _itemViews[[NSString stringWithFormat:@"%li", index]] = indexView;
    }
    // 存在则直接获取
    else {
        indexView = _itemViews[[NSString stringWithFormat:@"%li", index]];
        [_scroll addSubview:indexView];
    }
    // 设置frame，放到对应索引的位置去
    indexView.frame = CGRectMake(index * w, 0, w, h);
    // 添加到scroll上
    
    // 如果点击试题快速跳转到某一题时，要假装从当前可视的视图滚动到目标视图，因此需要移动currentVisableView的位置并改变contentOffset，这样看起来就好像没有移动一样
    if (index == _currentIndex) {}
    else if (index > _currentIndex) {
        
        currentVisableView.frame = CGRectMake(indexView.left - w, 0, w, h);
        _scroll.contentOffset = CGPointMake((index - 1) * w, 0);
        
    } else {
        
        currentVisableView.frame = CGRectMake(indexView.right, 0, w, h);
        _scroll.contentOffset = CGPointMake((index + 1) * w, 0);
    }
    
    // 滚动动画：从当前可视的视图滚动到目标视图，index == _currentIndex是不需要滚动，时间设为0即可
    [UIView animateWithDuration:index == _currentIndex ? 0 : 0.35 animations:^{
        
        self.scroll.contentOffset = CGPointMake(index * w, 0);
        
    } completion:^(BOOL finished) {
        
        if (finished) {
            
            if (index == self->_currentIndex) {
                if (number > 100000) {
                    //                    [indexView seekToFirst];
                } else if (number < -100000) {
                    //                    [indexView seekToLast];
                } else {
//                    [indexView seekToNumber:number];
                }
            } else {
//                [indexView seekToNumber:number];
            }
            
            // 如果可视视图不是目标视图，则需要移除可视视图
            if (index != self->_currentIndex) {
                [currentVisableView removeFromSuperview];
            }
            
            // 目标视图的下一题索引和上一题序索引
            NSInteger nextIndex = index + 1;
            NSInteger prevIndex = index - 1;
            
            // 目标视图不是最后一题，则需要创建下一题
            if (nextIndex < self->_maxCount) {
                
                KZExamItemView_v2 *nextView = nil;
                if (self.itemViews[[NSString stringWithFormat:@"%li", nextIndex]] == nil) {
                    
                    nextView = [KZExamItemView_v2 new];
                    nextView.model = self->_items[nextIndex];
                    [self.scroll addSubview:nextView];
                    self.itemViews[[NSString stringWithFormat:@"%li", nextIndex]] = nextView;
                }
                else {
                    nextView = self.itemViews[[NSString stringWithFormat:@"%li", nextIndex]];
                    [self.scroll addSubview:nextView];
                }
                nextView.frame = CGRectMake(indexView.right, 0, w, h);
            }
            
            // 目标视图不是第一题，则需要创建上一题
            if (prevIndex >= 0) {
                
                KZExamItemView_v2 *prevView = nil;
                if (self.itemViews[[NSString stringWithFormat:@"%li", prevIndex]] == nil) {
                    
                    prevView = [KZExamItemView_v2 new];
                    prevView.model = self->_items[prevIndex];
                    [self.scroll addSubview:prevView];
                    self.itemViews[[NSString stringWithFormat:@"%li", prevIndex]] = prevView;
                }
                else {
                    prevView = self.itemViews[[NSString stringWithFormat:@"%li", prevIndex]];
                    [self.scroll addSubview:prevView];
                }
                prevView.frame = CGRectMake(indexView.left - w, 0, w, h);
            }
        }
        
        // 视图全部设置完毕，可滑动
        self.scroll.scrollEnabled = true;
        // 修改当前可视视图的索引
        self->_currentIndex = index;
    }];
}


#pragma mark - 事件
- (void)onSelectNaviItem:(UIButton *)button {
    
}
@end

